package general;

import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Random;

import virtualdatagramsocket.VirtualDatagramSocket;

public class SocketHelper {
	
	/**
	 * Opens a new socket in a random port using the given host
	 * @param host The local host name
	 * @return A socket bound to a randomly chosen port
	 */
	public static VirtualDatagramSocket open(String host) throws UnknownHostException {
		/**
		 * Get a random port. Exclude the smallest port
		 * numbers, because they are often already in use.
		 */
		int port = 10000 + new Random().nextInt(55535);
		try {
			return new VirtualDatagramSocket(port, InetAddress.getByName(host));
		} catch (SocketException e) {
			return open(host);
		}
	}

}
